#include "common.h"
#include "pit.h"

extern int periph_clk_khz;

int pit_init(int pit, uint32 cnts){
    if(pit<0||pit>1)
        return -1;

    /* Enable PIT clock */
    SIM_SCGC6|=SIM_SCGC6_PIT_MASK;

    /* Enable PIT module, timers are enabled in debug mode */
    PIT_MCR&=~(PIT_MCR_FRZ_MASK|PIT_MCR_MDIS_MASK);

    /* Set timeout value */
    PIT_LDVAL(pit)=cnts;

    /* Clear PIT Interrupt Flag */
    PIT_TFLG(pit)=PIT_TFLG_TIF_MASK;

    /* Enable timer interrupt and start timer */
    PIT_TCTRL(pit)=(0|PIT_TCTRL_TEN_MASK);

    /* Enable Interrupt */
    enable_irq(22);

    return 0;
}

int pit_init_ms(int pit, uint32 ms){
    if(pit<0||pit>1)
        return -1;

    pit_init(pit, ms*periph_clk_khz-1); //24000 cycles per ms

    return 0;
}

void pit_enable(int pit){
    /* Enable timer interrupt */
    PIT_TCTRL(pit)|=(PIT_TCTRL_TEN_MASK|PIT_TCTRL_TIE_MASK);

    /* Enable Interrupt */
    enable_irq(22);
}

void pit_disable(int pit){
    /* Disable timer interrupt */
    PIT_TCTRL(pit)&=~(PIT_TCTRL_TIE_MASK);

    /* Disable Interrupt */
    disable_irq(22);
}
